/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { PureComponent } from "react";
import Iframe from "react-iframe";
import { Button } from "antd";
import styles from "./index.less";
import classname from "classnames";
import router from "umi/router";
import poster from "@kb/poster";
import { parse as queryParse } from "query-string";
export default class WebView extends PureComponent {
  constructor() {
    super();
  }

  //   刷新
  handleRefresh = () => {
    const { onRefresh } = this.props;
    const cwin = this.iframeNode.refs.iframe.contentWindow;
    poster.notify(cwin, { type: "reload" });
    try {
      onRefresh && onRefresh(queryParse(cwin.location.search));
    } catch (error) {
      console.info("[refresh-errmsg]", error);
    }
  };
  //   返回上一页
  handleGoBack = () => {
    const { onGoBack } = this.props;
    const cwin = this.iframeNode.refs.iframe.contentWindow;
    router.goBack();
    try {
      onGoBack && onGoBack(queryParse(cwin.location.search));
    } catch (error) {
      console.info("[goback-errmsg]", error);
    }
  };

  render() {
    const { url = "", hasbar = true, ...rest } = this.props;
    return (
      <div className={classname(styles.browser, hasbar && styles.hasbar)}>
        {hasbar && (
          <div className={styles.toolbar}>
            <Button icon="left" onClick={this.handleGoBack} />
            <Button icon="redo" onClick={this.handleRefresh} />
          </div>
        )}
        <div className={styles.iframe}>
          <Iframe ref={node => (this.iframeNode = node)} url={url} {...rest} />
        </div>
      </div>
    );
  }
}
